param($BuildVersion)

function Get-InSqlwwAdminToken()
{
    $InSqlwwAdminToken = [DataWorks.MI.Core.Item]::GetInstance("System.Security.Mappings.wwAdminToken")
    if ($InSqlwwAdminToken -eq $Null)
    {
        $InSqlwwAdminToken = New-FixedCredentials -UserName "wwAdmin" -Password "wwAdmin" -TokenName "wwAdminToken"
    }
    return $InSqlwwAdminToken
}


function New-FixedCredentials([string] $UserName, [string] $Password, [string] $TokenName)
{         
    Trap { [DataWorks.MI.Core.Persistence]::AbortTransaction(); [DataWorks.MI.Core.Persistence]::CloseTransaction(); throw }
    &{
        
        $SecurityPath = "Core."

        If ( $BuildVersion.Major -eq 3)
        {
            $SecurityPath = "Core.Security."
        }


        [DataWorks.MI.Core.Persistence]::BeginNewTransaction()
        
        #Get the Mappings collection property of the System.Security system item
        $SecurityItem = [DataWorks.MI.Core.Item]::GetInstance([DataWorks.MI.Core.Namespace.NamespaceProvider]::FQNSecurity)
        [DataWorks.MI.Core.IProperty] $ParentToAddTo = $SecurityItem.Properties["Mappings"]
        
        $ValueBag = New-Object -TypeName "DataWorks.MI.Core.Collections.NamedValueBag"
	
        $ValueBag.Add("SecurityMappingStrategyHolder", $SecurityItem)
        
        #Create new Security Strategy and add it to the System.Security.Mappings property
        $CredentialsStrategy = [DataWorks.MI.Core.Item]::CreateInstance([string] $($SecurityPath + "UseFixedCredentials"), $TokenName , [DataWorks.MI.Core.Collections.NamedValueBag] $ValueBag, [DataWorks.MI.Core.IProperty] $ParentToAddTo)
        
        $ValueBag.Clear()
    
        $ValueBag.Add("UserName", $UserName)
        $ValueBag.Add("Password", [DataWorks.MI.Core.Security.DataEncryptor]::Encrypt($Password))

        $MappedCredentialsProperty = $CredentialsStrategy.Properties["MappedCredentials"]
        
        #Create new SimpleCredential Login and add it to the new Security Strategy's MappedCredential collection property
        #Bug if create instance result is not assigned to variable
        $SimpleCredentials = [DataWorks.MI.Core.Item]::CreateInstance([string] $($SecurityPath + "SimpleCredentials"), "Credentials", $ValueBag, $MappedCredentialsProperty)

    
        [DataWorks.MI.Core.Persistence]::CommitTransaction()
        [DataWorks.MI.Core.Persistence]::CloseTransaction()
        
        
    
        return $CredentialsStrategy
    }
}


return Get-InSqlwwAdminToken








